package com.smiletrain.util;

import java.util.ArrayList;
import java.util.List;

import android.os.Environment;

import com.smiletrain.base.Alarma;

public class AdminAlarma {

	static {
		instance = new AdminAlarma();
	}
	
	private AdminAlarma(){ }
	
	public void loadAlarmas() {
		Alarma[] array = (Alarma[]) 
				Util.readObject(Environment.getExternalStorageDirectory().getAbsolutePath() + 
						Constantes.ALARM_PATH + Constantes.ALARM_FILE);
		
		alarmas.clear();
		
		if(array == null)
			return;
		
		for(Alarma a : array)
			alarmas.add(a);
		
	}
	
	public void saveAlarmas() {
		Alarma[] array = new Alarma[alarmas.size()];
		for(int i = 0 ; i < array.length ; i++)
			array[i] = alarmas.get(i);
		
		Util.writeObject(Environment.getExternalStorageDirectory().getAbsolutePath() + 
				Constantes.ALARM_PATH + Constantes.ALARM_FILE, array);
	}
	
	public int agregarAlarma(Alarma a) {
		int id = 0;

		if(alarmas != null && alarmas.size() != 0){
			int idt = alarmas.size();
			for(int i = 0 ; i < alarmas.size(); ){
				Alarma ct = alarmas.get(i);
				if(ct != null && ct.getId() == idt){
					idt++;
					i = 0;
					continue;
				}
				i++;
			}
			if(idt != 0)
				id = idt;
		}
		
		a.setId(id + 1);
		
		alarmas.add(a);
		
		return a.getId();
	}
	
	public Alarma getAlarma(int id){
		for(int i = 0 ; i < alarmas.size() ; i++)
			if(alarmas.get(i).getId() == id){
				return alarmas.get(i);
			}
		return null;
	}
	
	public List<Alarma> getAlarmas(){
		return alarmas;
	}
	
	public void eliminarAlarma(int r) {
		for(int i = 0 ; i < alarmas.size() ; i++)
			if(alarmas.get(i).getId() == r){
				alarmas.remove(i);
				break;
			}
		
		saveAlarmas();
	}
	
	private ArrayList<Alarma> alarmas = new ArrayList<Alarma>();
	
	public static AdminAlarma instance;
	
}
